package com.mocoop.jfqc;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.android.volley.Request.Method;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.mocoop.activity.MocoopActivity;

public class LoginActivity extends Activity {

	public static boolean isSingleton = true;
	private ImageView imageView;
	private EditText userName, passWord;
	private Button loginButton, configButton;
	private RequestQueue mQueue;
	private RelativeLayout loginProgress;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		mQueue = Volley.newRequestQueue(this);
		imageView = (ImageView) findViewById(R.id.configImg);
		userName = (EditText) findViewById(R.id.accountEdittext);
		passWord = (EditText) findViewById(R.id.pwdEdittext);
		loginButton = (Button) findViewById(R.id.loginButton);
		loginProgress = (RelativeLayout) findViewById(R.id.loginProgress);
		configButton = (Button) findViewById(R.id.configButton);

		imageView.setOnLongClickListener(new View.OnLongClickListener() {

			@Override
			public boolean onLongClick(View arg0) {

				userName.setText("chenchaowen");
				passWord.setText("admin");
				return false;
			}
		});

		loginButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				loginButton.setVisibility(View.GONE);
				loginProgress.setVisibility(View.VISIBLE);
				loginRequest();
				// startActivity(new Intent(LoginActivity.this,
				// TabHostMultitionActivity.class));
			}
		});
		configButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				startActivityForResult(new Intent(LoginActivity.this, LaunchActivity.class), 0);
			}
		});

		initApp();

	}

	public void initApp() {
		SharedPreferences sharedPreferences = getSharedPreferences("config", 0);

		MocoopActivity.setBASE_URL(sharedPreferences.getString("BASE_HTML_URL", MocoopActivity.getBASE_URL()));
		isSingleton = sharedPreferences.getBoolean("SINGLETON", true);
	}

	public void loginRequest() {
		String uname = userName.getText().toString();
		String pwd = passWord.getText().toString();
		JSONObject loginObject = null;
		String msgStr = "{\"username\":\"" + uname + "\",\"password\":\"" + pwd + "\"}";

		try {
			loginObject = new JSONObject(msgStr);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		/*if(true){
			SharedPreferences sharedPreferences = getSharedPreferences(MocoopActivity.MOCOOP_CONFIG, 0);
			Editor editor = sharedPreferences.edit();
			editor.putString(MocoopActivity.USER_ID, "100000048");
			editor.putString(MocoopActivity.USER_INFO,msgStr);
			editor.commit();
	
			if (!getIntent().getBooleanExtra(JFQCActivity.START_ACTIVITY_FOR_RESULT, false)) {

				if (isSingleton) {
					startActivity(new Intent(LoginActivity.this, MainActivity.class));
				} else {
					startActivity(new Intent(LoginActivity.this, TabHostMultitionActivity.class));
				}

				overridePendingTransition(R.anim.my_slide_in_from_left, R.anim.my_slide_still);
			}
			finish();
			
			return;
			
		}
		*/
		JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Method.POST, "https://qc.tradeicloud.com/QC/qclogin", loginObject,

		new Response.Listener<JSONObject>() {

			@Override
			public void onResponse(JSONObject response) {
				try {
					saveUser(response);
				} catch (JSONException e) {
					Toast.makeText(LoginActivity.this, "解析失败!", Toast.LENGTH_LONG).show();
				}
			}

		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				loginProgress.setVisibility(View.GONE);
				loginButton.setVisibility(View.VISIBLE);
				Log.d("RZZ", error.toString());
				if (error instanceof TimeoutError) {
					Toast.makeText(LoginActivity.this, "连接超时!", Toast.LENGTH_LONG).show();
				} else if (error instanceof NoConnectionError) {
					Toast.makeText(LoginActivity.this, "网络未连接!", Toast.LENGTH_LONG).show();
				}else if (error instanceof NetworkError) {
					Toast.makeText(LoginActivity.this, "Socket关闭，服务器宕机!", Toast.LENGTH_LONG).show();
				} else if (error instanceof ServerError) {
					Toast.makeText(LoginActivity.this, "服务器的响应了一个错误!", Toast.LENGTH_LONG).show();
				} else if (error instanceof ParseError) {
					Toast.makeText(LoginActivity.this, "服务端返回非json!", Toast.LENGTH_LONG).show();
				}else{
					Toast.makeText(LoginActivity.this, error.toString(), Toast.LENGTH_LONG).show();
				}
			}

		}) {
			@Override
			public Map<String, String> getHeaders() {
				HashMap<String, String> headers = new HashMap<String, String>();
				headers.put("Accept", "application/json");
				headers.put("Content-Type", "application/json; charset=UTF-8");
				return headers;
			}
		};

		mQueue.add(jsonRequest);
	}

	private String buildAppUUID() {
		return "S04" + UUID.randomUUID().toString().replaceAll("-", "");
	}

	private void saveUser(JSONObject response) throws JSONException {
		String returnCode = null;

		returnCode = response.getString("status");

		if (!"200".equals(returnCode)) {

			Toast.makeText(this, response.getString("exception"), Toast.LENGTH_LONG).show();

			loginProgress.setVisibility(View.GONE);
			loginButton.setVisibility(View.VISIBLE);
		} else {

			SharedPreferences sharedPreferences = getSharedPreferences(MocoopActivity.MOCOOP_CONFIG, 0);
			JSONObject userInfo = response.getJSONObject("record").getJSONObject("userInfo");
			String userID = userInfo.getString("userID");

			Editor editor = sharedPreferences.edit();
			editor.putString(MocoopActivity.USER_ID, userID);
			editor.putString(MocoopActivity.USER_INFO, userInfo.toString());
			editor.commit();

			JPushInterface.init(getApplicationContext());
			JPushInterface.resumePush(this);
			JPushInterface.setAlias(this, userID, new TagAliasCallback() {

				@Override
				public void gotResult(int arg0, String arg1, Set<String> arg2) {
					Log.d("RZZ", arg1 + "--------" + arg0);
				}
			});

			if (!getIntent().getBooleanExtra(JFQCActivity.START_ACTIVITY_FOR_RESULT, false)) {

				if (isSingleton) {
					startActivity(new Intent(LoginActivity.this, MainActivity.class));
				} else {
					startActivity(new Intent(LoginActivity.this, TabHostMultitionActivity.class));
				}

				overridePendingTransition(R.anim.my_slide_in_from_left, R.anim.my_slide_still);
			}
			finish();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		JPushInterface.onResume(this);

	};

	@Override
	protected void onPause() {
		super.onPause();
		JPushInterface.onPause(this);
	}
}
